import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HttpService {
  passHeader = new HttpHeaders();

  constructor(private http: HttpClient) {
    // 添加请求头
    this.passHeader.append('Content-Type', 'application/json;charset=utf-8');
  }

  /**
   * get请求
   * @param conf
   * @returns 调用接口
   */
  getData(conf: any) {
    return this.requestFn('get', conf);
  }

  /**
   * post请求
   * @param conf
   * @returns 调用接口
   */
  postData(conf: any) {
    return this.requestFn('post', conf);
  }

  /**
   * 获取请求头
   * @param newHeader
   * @returns {HttpHeaders}
   */
  getHeader(newHeader?: any) {
    if (newHeader) {
      for (const key of newHeader) {
        this.passHeader.append(key, newHeader[key]);
      }
    }
    return this.passHeader;
  }

  /**
   * 生成随机数
   * @param obj
   * @returns {*}
   */
  setHttpMath(obj: any) {
    const temp = obj || {};
    temp['_time'] = Math.random().toString();
    return temp;
  }

  /**
   * 调用接口方法
   * @param {string} method 请求地址
   * @param conf 请求参数
   * @returns {any}
   */
  private requestFn(method: string, conf: any) {
    let url = conf.url;
    const data: any = conf.data;
    const search = conf.search || {};
    const options: any = {
      headers: this.getHeader(conf.header || null),
      search: this.setHttpMath(search)
    };
    switch (method.toLocaleLowerCase()) {
      case 'get':
        return this.http.get(url, options);
      case 'post':
        if (url.indexOf('?') === -1) {
          url += '?_time=' + Math.random().toString();
        } else {
          url += '&_time=' + Math.random().toString();
        }
        return this.http.post(url, data, options);
    }
    return;
  }
}
